<?php
	require '../include/library.inc.php';
	require '../include/admin_login.inc.php';
	
	
$menu_id = $_GET['menu_id'];
	

if (!isset($_POST['is_submitted'])) {
	$_POST['is_submitted'] = '';
}
if (!isset($error_message)) {
	$error_message = '';
}	


if($_POST["redirect"] || $_SESSION['redirect'] ){
	if($_POST["redirect"]) $redirect = $_POST["redirect"];
	if($_SESSION['redirect']){ 
	$redirect = $_SESSION['redirect'];
	unset($_SESSION['redirect']);
	}
}else{
       $redirect = $_SERVER['HTTP_REFERER'];	
     }	
	 	
	if ($_POST['is_submitted']) {
		$error_message = '';
		$redirect = $_POST["redirect"];
    
	
	
	if (!$_POST['title'])  $error_message .= 'Не е въведено заглавие!<br/>';
		
    if(!$error_message) {
		
		
		//Запис на меню
		
		$sql = "UPDATE menus SET
				  title = '".escape($_POST['title'])."',
				  menuitems = '".$_POST['output']."',
				  published = '".intval($_POST['published'])."'
				WHERE
				 menu_id = '".$menu_id."'
				";
				  
		query($sql);
		
		
		$sql = "DELETE FROM 
				   menu_description
				WHERE
				   menu_id = '".$menu_id."'
				 ";
		query($sql);
		
		
		$titles = explode("],",$_POST['titledata']);
		$echo = sizeof($titles);
		  for($u = 0; $u < sizeof($titles)-1; $u++)
		   {   
		   
		   			
		   		$val = explode(",",str_replace('"','',substr($titles[$u],1)));
				
				for($i = 2; $i < sizeof($val);  $i++)
				{
					
				$title = $val[$i];
				$item_id = $val[0];
				$parent_id =$val[1];
				
				$sql = "INSERT INTO menu_description
				  (menu_id,lang_id,item_id,parent_id,title)
				VALUES
				  ('".$menu_id."','".($i-1)."','".$item_id."','".$parent_id."','".$title."')";
				 
		        query($sql);
				}
		   }
		
			
		
		
		
		$_SESSION['message'] .= 'Редакцията е записана успешно!';
         
		 redirect(HTML_BASE_ADMIN.'/menu_edit.php?menu_id='.$menu_id);
		   
		
		
    }

}
  	$sql= "SELECT menuitems,title,published FROM
							menus
						   WHERE
							menu_id = '".$menu_id."'
							
						  ";
	$result = query($sql);
	$row_m = mysql_fetch_object($result);
	if(!$_POST['is_submit'])
	{
		$_POST['title'] = $row_m->title;
		$_POST['published'] = $row_m->published;
	}
	
	head_admin("Редактиране на меню");
	
	
?>


    

		
            <?php if ($error_message) { ?>
			<div class="message red">
				<h3>Грешка!</h3>
				<?=$error_message?>
			</div>
			<?php } ?>
            
             <?php if ($_SESSION['message']) { ?>
    		<div class="message green">
       			 <?=$_SESSION['message']?>
    		</div>
			<?php unset($_SESSION['message']); } ?>
			
            <div class="topbuttons">
            	<a href="<?=$redirect?>">Обратно</a>
            </div>
			
            <h3>Редактиране на меню</h3>
			            
            <form id="new_menu" action="<?=$_SERVER['PHP_SELF']?>?<?=$_SERVER['QUERY_STRING']?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="is_submitted" value="1" />
            <input id="redirectForm" type="hidden" name="redirectForm" value="" />
            <input type="hidden" name="redirect" value="<?=$redirect?>" />	
			<input type="hidden" id="output" name="output"/>
			<input type="hidden" id="titledata" name="titledata"/>					
			
            <dl>
			<label class="required">Заглавие:</label>
        	<input class="inputbox" name="title" type="text" value="<?=$_POST['title']?>" >
			<input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($_POST['published'])?"checked=\"checked\"":"")?> />
			<label>Публикуванo</label>
            
            <a style="float:right" class="button" href="#" onClick="senditem(); return false;">запиши</a>  
			</dl>
						
			</form>  
          
          

         <div style="width:30%; float:left;">
		 	
			<h4>Добави връзка</h4>
			
         <ul class="type-box">
         	<?php
			
				function get_original_title($id)
				{
					$sql= "SELECT d.title FROM
							page_description AS d
						   WHERE
							d.page_id = '".$id."'
							ORDER BY    d.lang_id
						  ";
						$result = query($sql);
						
						$arr = "";	
						while ($row = mysql_fetch_object($result)) {
							
							$arr .= '|'.$row->title;
						}
						
						return $arr;
				}
				$lang = 1;
				$sql_c = "SELECT
							c.page_id,
							c.order_number,
							c.published,
							
							d.title
							
						FROM
							pages AS c,
							page_description AS d
						WHERE
						
							c.page_id = d.page_id
							
							AND
							
							d.lang_id = '".$lang."'
							
							ORDER BY c.order_number DESC
						  ";
						$result_c = query($sql_c);
							
						while ($row = mysql_fetch_object($result_c)) {
                          ?>
                        <li>
                        <a href="#" onClick="additem(<?=$row->page_id?>,'<?=get_original_title($row->page_id)?>'); return false;"><?=$row->title?> &raquo;</a>
                         
                        </li>
        			<?php  } ?>
				</ul>
         
         </div>
 
  
    <div class="cf nestable-lists" >
		
		
		<h4>Структура</h4>

        <div class="dd" id="nestable3" >
            
            <?php 
				
				
				
				
			
		
		 $arr =  json_c_decode($row_m->menuitems);
		 $_SESSION['leval']  = 0;
		 
		 $sqlmax = "SELECT MAX(item_id) AS maxitem FROM menu_description WHERE menu_id = '".$menu_id."'";
		 $rowmax = mysql_fetch_object(query($sqlmax)); 
		 
		 function create_ul($ar,$first)
		 {
				$menu_id = $_GET['menu_id'];
				if($first)
				{
					echo '<ol id="cover-item" class="dd-list" >';
				}else{
				  echo '<ol class="dd-list" >';
				}
				foreach ($ar as $key => $value) {
				 
				
				$item = $value['id'];
				
				$sqlm =  "SELECT 
						m.parent_id,
						m.title
						
					FROM 
					menu_description AS m
					WHERE 
					 m.menu_id = '".$menu_id."'
					 AND m.item_id = '".$item."'
					 AND m.lang_id = '1'
					 ";
			
			$rowm = mysql_fetch_object(query($sqlm)); 
				 
			$tamplate  = '<li class="dd-item dd3-item" data-id="'.$item.'" id="id-'.$item.'">
			<div class="dd-handle dd3-handle"></div><div class="dd3-content">'.$rowm->title.'  </div>
			<div class="act-btns">
			<a class="edit" title="Редактирай" href="#" onClick="edititem('.$item.'); return false;">Редактирай</a>  <a class="delete" title="Изтрий" href="#" onClick="deleteitem('.$item.'); return false;">Изтрий</a></div>
			<div class="menu-titles" id="input'.$item.'">
			<input type="hidden"  value="'.$rowm->parent_id.'" />';
 	
			$sqll =  "SELECT 
						m.lang_id,
						m.title,
						l.Name
					FROM 
					menu_description AS m,
					language AS l
					
					WHERE 
					 m.menu_id = '".$menu_id."'
					 AND m.item_id = '".$item."'
					 AND m.lang_id = l.lang_id
					 
					 ORDER BY lang_id
					 ";
			$resultl = query($sqll);
			
			while ($row_lang = mysql_fetch_object($resultl)) {
				
				
			
			$tamplate .= '<label>'.$row_lang->Name.'</label> <input class="inputbox w250"  value="'.$row_lang->title.'"/><br/>';
			
			 }
$tamplate .= '</div>';
	
				 
				 
				 
				 
				 echo $tamplate;
				 if($value['children']) create_ul($value['children'],false);
				 
					echo '</li>';
				}
				echo '</ol>';
				
				
		 }
		 
		 create_ul($arr,true);
					
			
			?>
                
            
        </div>

    </div>
  
  
  
<script type="text/javascript" src="js/jquery.nestable.js"></script>
<script type="text/javascript">

                    

$(document).ready(function()
{

    var updateOutput = function(e)
    {
        var list   = e.length ? e : $(e.target),
            output = list.data('output');
        if (window.JSON) {
            output.val(window.JSON.stringify(list.nestable('serialize')));//, null, 2));
        } else {
            output.val('JSON browser support required for this demo.');
        }
    };

   

    $('#nestable-menu').on('click', function(e)
    {
        var target = $(e.target),
            action = target.data('action');
        if (action === 'expand-all') {
            $('.dd').nestable('expandAll');
        }
        if (action === 'collapse-all') {
            $('.dd').nestable('collapseAll');
        }
    });

    $('#nestable3').nestable();
	
	
	// activate Nestable for list 2
    $('#nestable3').nestable({
        group: 1
    })
    .on('change', updateOutput);

    // output initial serialised data
    updateOutput($('#nestable3').data('output', $('#output')));
	
	


});


var menuitems = (<?=$rowmax->maxitem?>+1);
function additem(itemid,itm)
{
	var titleitm = itm.split("|");
	var title = titleitm[1];
	var tamplate  = '<li class="dd-item dd3-item" data-id="' + menuitems + '" id=\"id-' + menuitems + '">\n <div class="dd-handle dd3-handle"></div><div class=\"dd3-content">'+title+'  </div><div class="act-btns"><a class="edit" title="Редактирай" href="#" onClick="edititem(' + menuitems +'); return false;">Редактирай</a>  <a class="delete" title="Изтрий" href="#" onClick="deleteitem(' + menuitems +'); return false;">Изтрий</a></div> \n <div class="menu-titles" id="input' + menuitems +'"> \n <input type="hidden"  value="'+itemid+'" />			';
 <?php 
			
			$sql = 'SELECT lang_id,Name,code
					FROM language
					WHERE published';
			$result = query($sql);
			
			
			while ($row_lang = mysql_fetch_object($result)) {
				
			?>
			tamplate += '<label><?=$row_lang->Name?></label> <input class="inputbox w250" value="'+ titleitm[<?=$row_lang->lang_id?>]+'"/><br/>';
			
			<?php
			 }?>
tamplate += '</div>\n</li>';
	
	
	$('#cover-item').append(tamplate);
	$('#nestable3').change();
	
	menuitems++;
}

function deleteitem(id)
{
	var answer = confirm("Внимание! Ще бъдат изтрити и елемeтите свързани с този. Изтриване?")
		if (answer){
			  $('#id-'+id).remove();
			  $('#nestable3').change();
		}
}

function edititem(id)
{
	$('#input'+id).toggle(200);
}

function senditem()
{
	var str = '';
	$( ".dd-item" ).each(function() {
		
		str += '["'+$( this ).attr('data-id');
		var ie = $( this ).attr('data-id');
  		
		$( '#input'+ie+' input').each(function() {
			str += '","'+ $( this ).val();
		});
		str += '"],';
	});
	
	
	$('#titledata').val(str);
	$('#nestable3').change();
	 
	$('#new_menu').submit();
}
</script>
            
<?php
	foot_admin(); 
?>